/**
 * KopsoxApplicationServices
 * Copyright (C) 2010 Free Software Foundation, Inc. <http://fsf.org/>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.kopsox.services.message;

import java.util.HashSet;
import java.util.Set;

/**
 * Abstract implementation of MessageConsumer.
 * NOTE: If the sender is the same as the consumer, the message will be not serviceable!
 * 
 * @author Konrad Renner
 *
 */
public abstract class AbstractMessageConsumer implements MessageConsumer {

	protected final Set<MessageFilter> filters;
	
	public AbstractMessageConsumer() {
		this(new HashSet<MessageFilter>());
	}
	
	public AbstractMessageConsumer(Set<MessageFilter> filters) {
		this.filters = filters;
		appendAnnotatedFilters();
		
		filters.add(new MessageFilter() {
			
			@Override
			public boolean isMessageServiceable(MessageConsumer cons, SimpleMessage message) {
				
				return ! cons.equals(message.getSender());
			}
		});
	}
	
	private final void appendAnnotatedFilters() {
		if(getClass().isAnnotationPresent(MessageFilters.class)) {
			MessageFilters afilters = getClass().getAnnotation(MessageFilters.class);
			
			try {
				for(Class<? extends MessageFilter> filter : afilters.filters()) {
					filters.add(filter.newInstance());
				}
			}catch(Exception e) {
				throw new IllegalStateException("Problem creating MessageFilters:"+e,e);
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.kopsox.services.message.MessageConsumer#isMessageServiceable(org.kopsox.services.message.SimpleMessage)
	 */
	@Override
	public boolean isMessageServiceable(SimpleMessage message) {
		
		for(MessageFilter filter : filters) {
			if(!filter.isMessageServiceable(this, message)) {
				return false;
			}
		}
		
		return true;
	}

	@Override
	public abstract int hashCode();

	@Override
	public abstract boolean equals(Object obj);
}
